package eai.tp2.lpco.web.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import eai.tp2.lpco.credentials.auth.IAuthentication;
import eai.tp2.lpco.web.beans.UserBean;
import eai.tp2.lpco.web.beans.ErrorList;

/**
 * Servlet implementation class Authentication
 */
public class Authentication extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Authentication() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (username != null && password != null) {
			IAuthentication auth = null;
			InitialContext ctx = null;
			try {
				ctx = new InitialContext();
				auth = (IAuthentication) ctx.lookup("AuthenticationBean/remote");			
			} catch (NamingException e) {			
				e.printStackTrace();
			}			
			if (auth.login(username, password)) {
				UserBean user = new UserBean();
				user.setUsername(username);
				session.setAttribute("user", user);
				response.sendRedirect("list.jsp");	
			} else {
				String error;
				error = "Wrong username or password. Try again.";
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);			
			}
		} else {			
			String error;
			error = "username field or password field are null.";			
			List<String> errors = new ArrayList<String>();
			errors.add(error);
			ErrorList list = new ErrorList();
			list.setErrorList(errors);		
			request.setAttribute("list", list);
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);			
		}
	}

}
